from django import forms
from crm import models
from multiselectfield.forms.fields import MultiSelectFormField
import hashlib

# class RegForm(forms.Form):
#     username = forms.EmailField()
#     passwor = forms.CharField(
#         widget=forms.PasswordInput()
#     )


from django.core.exceptions import ValidationError


class BSForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # 自定义操作
        for name, field in self.fields.items():

            if isinstance(field, (MultiSelectFormField, forms.BooleanField)):
                continue
            field.widget.attrs['class'] = 'form-control'


class RegForm(forms.ModelForm):
    password = forms.CharField(min_length=6,
                               widget=forms.PasswordInput(attrs={'placeholder': '密码', 'autocomplete': 'off'}))
    re_password = forms.CharField(min_length=6,
                                  widget=forms.PasswordInput(attrs={'placeholder': '确认密码', 'autocomplete': 'off'}))

    class Meta:
        model = models.UserProfile
        fields = '__all__'  # ['username']
        exclude = ['is_active']

        widgets = {
            'username': forms.TextInput(attrs={'placeholder': '用户名', 'autocomplete': 'off'}),
            'password': forms.PasswordInput(attrs={'placeholder': '密码', 'autocomplete': 'off'}),
            'name': forms.TextInput(attrs={'placeholder': '真实姓名', 'autocomplete': 'off'}),
            'mobile': forms.TextInput(attrs={'placeholder': '手机号', 'autocomplete': 'off'}),

        }

        labels = {
            'username': 'xxx'
        }

        error_messages = {
            'username': {}
        }

    def clean(self):
        self._validate_unique = True  # 到数据库校验唯一
        password = self.cleaned_data.get('password', '')
        re_password = self.cleaned_data.get('re_password')
        if password == re_password:
            md5 = hashlib.md5()
            md5.update(password.encode('utf-8'))
            self.cleaned_data['password'] = md5.hexdigest()
            return self.cleaned_data
        self.add_error('re_password', '两次密码不一致!!')
        raise ValidationError('两次密码不一致')


class CustomerForm(BSForm):
    class Meta:
        model = models.Customer
        fields = "__all__"  # []
        exclude = []

        # widgets = {
        #     'qq':forms.TextInput(attrs={'class':'form-control'}),
        #
        # }
        # labels ={}
    #


class ConsultRecordForm(BSForm):
    class Meta:
        model = models.ConsultRecord
        fields = '__all__'

    def __init__(self, request, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # 限制客户为当前用户的私户

        print(list(self.fields['customer'].choices))
        # self.fields['customer'].choices=[('', '---------'), (1, '1231231298798 - alex'), (2, '987987234 - alexdsb')]
        # self.fields['customer'].choices = request.user_obj.customers.values_list('id', 'name')
        self.fields['customer'].choices = [('', '---------')] + [(i.pk, str(i)) for i in
                                                                 request.user_obj.customers.all()]

        # 限制跟进人为当前的用户
        self.fields['consultant'].choices = [(request.user_obj.pk, request.user_obj)]


class EnrollmentForm(BSForm):
    class Meta:
        model = models.Enrollment
        fields = '__all__'

    def __init__(self, customer_id, *args, **kwargs):
        super().__init__(*args, **kwargs)

        customer_obj = models.Customer.objects.filter(pk=customer_id).first() if customer_id else self.instance.customer

        self.fields['customer'].choices = [(customer_obj.pk, customer_obj), ]
        self.fields['enrolment_class'].choices = [('', '---------')] + [(i.pk, str(i)) for i in
                                                                        customer_obj.class_list.all()]


class EnrollmentForm(BSForm):
    class Meta:
        model = models.Enrollment
        fields = '__all__'

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        customer_obj = self.instance.customer

        self.fields['customer'].choices = [(customer_obj.pk, customer_obj), ]
        self.fields['enrolment_class'].choices = [('', '---------')] + [(i.pk, str(i)) for i in
                                                                        customer_obj.class_list.all()]


class ClassForm(BSForm):
    class Meta:
        model = models.ClassList
        fields = '__all__'


class CourseRecordForm(BSForm):
    class Meta:
        model = models.CourseRecord
        fields = '__all__'

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        self.fields['re_class'].choices = [(self.instance.re_class_id, self.instance.re_class), ]
        self.fields['recorder'].choices = [(self.instance.recorder_id, self.instance.recorder), ]


class StudyRecordForm(BSForm):
    class Meta:
        model = models.StudyRecord
        fields = '__all__'
